﻿//using System.Windows.Controls;
//using Windows.UI.Xaml.Navigation;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.Web.Syndication;

namespace TR1app.DataModel
{
    // FeedData
    // Holds info for a single blog feed, including a list of blog posts (FeedItem)
    public class FeedData
    {
        private List<FeedItem> _Items = new List<FeedItem>();

        public string Description { get; set; }

        public List<FeedItem> Items
        {
            get
            {
                return this._Items;
            }
        }

        public DateTime PubDate { get; set; }

        public string Title { get; set; }
    }

    // FeedDataSource
    // Holds a collection of blog feeds (FeedData), and contains methods needed to
    // retreive the feeds.
    public class FeedDataSource
    {
        private ObservableCollection<FeedData> _Feeds = new ObservableCollection<FeedData>();

        public ObservableCollection<FeedData> Feeds
        {
            get
            {
                return this._Feeds;
            }
        }

        // Returns the feed that has the specified title.
        public static FeedData GetFeed(string title)
        {
            // Simple linear search is acceptable for small data sets
            var _feedDataSource = App.Current.Resources["feedDataSource"] as FeedDataSource;

            var matches = _feedDataSource.Feeds.Where((feed) => feed.Title.Equals(title));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        // Returns the post that has the specified title.
        public static FeedItem GetItem(string uniqueId)
        {
            // Simple linear search is acceptable for small data sets
            var _feedDataSource = App.Current.Resources["feedDataSource"] as FeedDataSource;
            var _feeds = _feedDataSource.Feeds;

            var matches = _feedDataSource.Feeds.SelectMany(group => group.Items).Where((item) => item.Title.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public async Task GetFeedsAsync()
        {
            Task<FeedData> feed1 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_top_stories");
            Task<FeedData> feed2 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_computing");
            Task<FeedData> feed3 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_web");
            Task<FeedData> feed4 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_communications");
            Task<FeedData> feed5 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_energy");
            Task<FeedData> feed6 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_biotech");
            Task<FeedData> feed7 =
                GetFeedAsync("http://feeds.technologyreview.com/technology_review_biztech");
            this.Feeds.Add(await feed1);
            this.Feeds.Add(await feed2);
            this.Feeds.Add(await feed3);
            this.Feeds.Add(await feed4);
            this.Feeds.Add(await feed5);
            this.Feeds.Add(await feed6);
            this.Feeds.Add(await feed7);
        }

        private async Task<String> GetContentAsync(Uri UrlString)
        {
            var client = new HttpClient();
            try
            {
                var response = await client.GetAsync(UrlString);
                var result = await response.Content.ReadAsStringAsync();

                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }


        private async Task<FeedData> GetFeedAsync(string feedUriString)
        {
            Windows.Web.Syndication.SyndicationClient client = new SyndicationClient();
            Uri feedUri = new Uri(feedUriString);

            try
            {
                SyndicationFeed feed = await client.RetrieveFeedAsync(feedUri);

                // This code is executed after RetrieveFeedAsync returns the SyndicationFeed.
                // Process the feed and copy the data we want into our FeedData and FeedItem classes.
                FeedData feedData = new FeedData();

                feedData.Title = feed.Title.Text;
                if (feed.Subtitle != null && feed.Subtitle.Text != null)
                {
                    feedData.Description = feed.Subtitle.Text;
                }

                // Use the date of the latest post as the last updated date.
                feedData.PubDate = feed.Items[0].PublishedDate.DateTime;
                int limit = 0;
                foreach (SyndicationItem item in feed.Items)
                {
                    FeedItem feedItem = new FeedItem();
                    feedItem.Title = item.Title.Text;
                    feedItem.PubDate = item.PublishedDate.DateTime;

                    // Handle the differences between RSS and Atom feeds.
                    if (feed.SourceFormat == SyndicationFormat.Atom10)
                    {
                        //feedItem.Link = new Uri("http://windowsteamblog.com" + item.Id);
                    }
                    else if (feed.SourceFormat == SyndicationFormat.Rss20)
                    {
                        feedItem.Description = item.Summary.Text;
                        feedItem.Link = item.Links[0].Uri;
                    }

                    foreach (var extension in item.ElementExtensions)
                    {
                        String ele = extension.ToString();
                        if (extension.NodeName == "origLink")   /// this gets the URL link to the original topic
                            feedItem.ContentLink = new Uri(extension.NodeValue);
                    }
                    limit++;
                  //  await GetBackgroundInfoForContent_Async(feedItem);
                    feedData.Items.Add(feedItem);
                    if (limit >= 50) break;  // only read the first 50 articals in any news feed
                }
                return feedData;
            }
            catch (Exception)
            {
                return null;
            }
        }



        private async Task GetItemContent(FeedItem feedItem)
        {
            var webGet = new HtmlWeb();
            var document = await webGet.LoadFromWebAsync(feedItem.ContentLink.AbsoluteUri);
            String response = new String('a', 1);
            var divTags = document.DocumentNode.Descendants("section");
            HtmlNode ArticalNode = null;
            HtmlNode AuthorInfo = null;
            HtmlNode ExploreInfo = null;
            HtmlNode CommentsInfo = null;

            foreach (var tag in divTags)
            {
                if (tag.Attributes[0] != null && tag.Attributes[0] != null)
                {
                    if (tag.Attributes[0].Value == "main-artical") // contains the Link to the Autor Bio etc
                        AuthorInfo = tag;
                    if (tag.Attributes[0].Value == "body")  // this is the actual Atrical text
                    {
                        ArticalNode = tag;
                        response = ArticalNode.InnerHtml;
                    }
                    if (tag.Attributes[0].Value == "authors") // contains the Link to the Autor Bio etc
                        AuthorInfo = tag;
                    if (tag.Attributes[0].Value == "explore") // contains the Link to the Autor Bio etc
                        ExploreInfo = tag;
                    if (tag.Attributes[0].Value == "comments") // contains the Link to the Autor Bio etc
                        CommentsInfo = tag;
                }
            }
            feedItem.Description = response; // update the feed content
        }
    
    }

    // FeedItem
    // Holds info for a single post
    public class FeedItem
    {
        public string Category { get; set; }

        public Uri ContentLink { get; set; }

        public string Description { get; set; }

        public Uri ImageLink { get; set; }

        public Uri Link { get; set; }

        public DateTime PubDate { get; set; }

        public string Title { get; set; }
    }
}